<template>
  <basic-container>
    <el-tabs type="border-card" style="margin: 10px">
      <el-tab-pane label="维修登记搜索">
        <avue-form ref="badConfirmProperties" v-model="badCodeModel" :option="badCodeOption">
          <template slot="productSequenceNumber">
            <el-input ref="sequenceNumberProperties" placeholder="请输入产品序列号" v-model="badCodeModel.productSequenceNumber" @keyup.enter.native="submitBadCode" clearable>
            </el-input>
          </template>
          <template slot="packingSn">
            <el-input ref="packingSnProperties" placeholder="请输入包装条码" @keyup.enter.native="submitBadCode" v-model="badCodeModel.packingSn" clearable> </el-input>
          </template>
          <template slot="vehicleSn">
            <el-input ref="vehicleSnProperties" placeholder="请输入载具编码" @keyup.enter.native="submitBadCode" v-model="badCodeModel.vehicleSn" clearable> </el-input>
          </template>
        </avue-form>
      </el-tab-pane>
    </el-tabs>
    <el-tabs type="border-card" style="margin: 10px">
      <el-tab-pane label="维修登记明细">
        <el-table
          height="calc(100vh - 426px)"
          :data="data"
          border
          @row-dblclick="rowDblclick"
          style="width: 100%"
          header-row-class-name="header-color"
          :row-class-name="tableRowClassName"
        >
          <el-table-column v-for="item in column" :label="item.label" :width="item.width" style="color: #25252" :prop="item.prop" :key="item.prop" :formatter="item.formatter">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button icon="el-icon-view" size="mini" type="text" @click="viewDetail(scope.$index, scope.row)" v-if="permission.repairrecord_view">详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="footer">
          <el-button type="primary" size="small" icon="el-icon-arrow-right" @click="handleRepair" v-if="permission.repairrecord_repair" :disabled="!selectionList.length"
            >进维修
          </el-button>
          <el-button icon="el-icon-delete" size="small" @click="reset">清 空</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog append-to-body :close-on-click-modal="false" title="选择维修站" :visible.sync="showDialog" width="40%" top="5vh" @open="repairrecordOpen">
      <avue-form ref="properties" v-model="properties" :option="propertiesOption" @submit="onSubmit"></avue-form>
    </el-dialog>

    <el-dialog append-to-body :close-on-click-modal="false" title="详情" :visible.sync="viewDialog" width="50%" top="20vh">
      <repairDetail :rowData="rowData" :isAuto="isAuto" :activeName="activeName">
        <table border="1" cellspacing="0" cellpadding="0" style="width: 100%">
          <tbody style="border: 1px solid #ebeef5">
            <tr style="height: 40px">
              <td class="tdStyle">序列号:</td>
              <td style="width: 300px">{{ rowData.productSequenceNumber }}</td>
              <td class="tdStyle">条码类型:</td>
              <td style="width: 300px" v-if="rowData.objectType == 'PRODUCT'">产品</td>
              <td style="width: 300px" v-else>载具</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">产品数量:</td>
              <td>{{ rowData.quantity }}</td>
              <td class="tdStyle">不良来源:</td>
              <td>{{ rowData.registrySource }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">当前所处工序:</td>
              <td>{{ rowData.currRouteName }}</td>
              <td class="tdStyle">不良产生工序:</td>
              <td>{{ rowData.fromRouteName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良代码:</td>
              <td>{{ rowData.failureCode }}</td>
              <td class="tdStyle">不良现象描述:</td>
              <td>{{ rowData.failureName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良登记人员:</td>
              <td>{{ rowData.confirmByName }}</td>
              <td class="tdStyle">不良登记时间:</td>
              <td>{{ rowData.registryDate }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良原因大类:</td>
              <td style="width: 300px">{{ rowData.mainCauseName }}</td>
              <td class="tdStyle">不良原因小类:</td>
              <td style="width: 300px">{{ rowData.subCauseName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">不良确认人员:</td>
              <td style="width: 300px">{{ rowData.confirmByName }}</td>
              <td class="tdStyle">不良确认时间:</td>
              <td style="width: 300px">{{ rowData.confirmTime }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">工单号:</td>
              <td>{{ rowData.workOrderNo }}</td>
              <td class="tdStyle">车间:</td>
              <td style="width: 300px">{{ rowData.workshopName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">产线:</td>
              <td style="width: 300px">{{ rowData.lineName }}</td>
              <td class="tdStyle">产品名称:</td>
              <td style="width: 300px">{{ rowData.partName }}</td>
            </tr>
            <tr style="height: 40px">
              <td class="tdStyle">产品编码:</td>
              <td style="width: 300px">{{ rowData.partNo }}</td>
              <td class="tdStyle">产品型号:</td>
              <td style="width: 300px">{{ rowData.partModel }}</td>
            </tr>
          </tbody>
        </table>
      </repairDetail>
    </el-dialog>
  </basic-container>
</template>

<script>
import repairDetail from '@/components/repair/detail.vue';
import { getList, submit, getCenterList } from '@/api/repair/repairrecord';
import { mapGetters } from 'vuex';

export default {
  name: 'RepairRepairRecord',
  components: {
    repairDetail
  },
  data() {
    return {
      isAuto: false,
      activeName: 'first',
      user_id: '',
      badCodeModel: { objectType: 'PRODUCT', productSequenceNumber: '' },
      badCodeOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '条码类型',
            prop: 'objectType',
            labelWidth: 100,
            search: true,
            span: 6,
            type: 'select',
            value: 'PRODUCT',
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ],
            control: (val, form) => {
              if (form.objectType == 'PRODUCT') {
                return {
                  productSequenceNumber: {
                    display: true
                  },
                  packingSn: {
                    display: false
                  },
                  vehicleSn: {
                    display: false
                  }
                };
              } else if (form.objectType == 'PACKING') {
                return {
                  productSequenceNumber: {
                    display: false
                  },
                  packingSn: {
                    display: true
                  },
                  vehicleSn: {
                    display: false
                  }
                };
              } else if (form.objectType == 'CARRIER') {
                return {
                  productSequenceNumber: {
                    display: false
                  },
                  packingSn: {
                    display: false
                  },
                  vehicleSn: {
                    display: true
                  }
                };
              }
            },
            change: ({ value }) => {
              if (value == 'PRODUCT') {
                this.badCodeModel.packingSn = '';
                this.badCodeModel.vehicleSn = '';
              } else if (value == 'PACKING') {
                this.badCodeModel.productSequenceNumber = '';
                this.badCodeModel.vehicleSn = '';
              } else if (value == 'CARRIER') {
                this.badCodeModel.packingSn = '';
                this.badCodeModel.productSequenceNumber = '';
              }
            },
            rules: [
              {
                required: true,
                message: '请选择条码类型',
                trigger: 'change'
              }
            ]
          },
          {
            label: '产品序列号',
            prop: 'productSequenceNumber',
            labelWidth: 100,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入产品序列号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '包装条码',
            prop: 'packingSn',
            labelWidth: 100,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入包装条码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '载具编码',
            prop: 'vehicleSn',
            labelWidth: 100,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入载具编码',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      column: [
        {
          label: '序列号',
          prop: 'productSequenceNumber',
          minWidth: 150,
          search: true
        },
        {
          label: '工单号',
          prop: 'workOrderNo'
        },
        {
          label: '条码类型',
          prop: 'objectType',
          formatter: (row, column) => {
            if (row.objectType == 'PRODUCT') {
              return '产品';
            } else {
              return '载具';
            }
          }
        },
        {
          label: '产品数量',
          prop: 'quantity'
        },
        {
          label: '不良来源',
          prop: 'registrySource'
        },
        {
          label: '当前所处工序',
          prop: 'currRouteName'
        },
        {
          label: '不良产生工序',
          prop: 'fromRouteName'
        },
        {
          label: '不良代码',
          prop: 'failureCode'
        },
        {
          label: '不良现象描述',
          prop: 'failureName',
          row: true
        }
      ],
      form: {},
      query: {},
      loading: false,
      showDialog: false,
      viewDialog: false,
      rowData: {},
      selectionList: [],
      properties: {
        workshopId: '',
        repairStationId: ''
      },
      serchIds: [],
      productSequenceNumber: '',
      propertiesOption: {
        column: [
          {
            label: '车间',
            prop: 'workshopId',
            type: 'select',
            // dicUrl: '/api/mes-product/productionline/query-workshop-line-list',
            dicUrl: '/api/mes-admin/workshop/key-value',
            props: {
              label: 'workshopName',
              value: 'workshopId'
            },
            dicFormatter: (data) => {
              return data.data;
            },
            cascader: ['repairStationId']
          },
          {
            label: '维修站',
            prop: 'repairStationId',
            type: 'select',
            dicFlag: false,
            dicUrl: '/api/mes-product/mro/operatingcenter/list?workshopId={{key}}',
            props: {
              label: 'name',
              value: 'id'
            },
            dicFormatter: (data) => {
              return data.data;
            },
            rules: [
              {
                required: true,
                message: '请输入维修站',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      data: []
    };
  },
  mounted() {
    this.onLoad();
    const userInfo = JSON.parse(localStorage.getItem('saber-userInfo'));
    if (userInfo && userInfo.content.user_id) {
      this.user_id = userInfo.content.user_id;
    }
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  methods: {
    onLoad(params = {}, title) {
      this.loading = true;
      let that = this;
      getList(params).then((res) => {
        const data = res.data.data;
        this.data = data;
        this.data.forEach((item) => {
          if (item.registrySource === 'AUTO') {
            item.registrySource = '自动';
          } else if (item.registrySource === 'MANUAL') {
            item.registrySource = '手动';
          }
        });
        this.loading = false;
      });
    },
    onSubmit() {
      this.$refs.properties.validate((valid, done) => {
        if (valid) {
          submit(this.ids, this.properties.workshopId, this.properties.repairStationId).then((res) => {
            this.showDialog = false;
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.onLoad();
            this.serchIds = [];
          });
        }
        done();
      });
    },
    handleRepair() {
      this.showDialog = true;
    },
    reset() {
      this.data = [];
    },

    //根据序列号录入序列号
    async submitBadCode() {
      this.$refs.badConfirmProperties.validate((valid, done) => {
        if (valid) {
          let productSequenceNumber = '';
          if (this.badCodeModel.objectType == 'PRODUCT') {
            productSequenceNumber = this.badCodeModel.productSequenceNumber;
          } else if (this.badCodeModel.objectType == 'PACKING') {
            productSequenceNumber = this.badCodeModel.packingSn;
          } else if (this.badCodeModel.objectType == 'CARRIER') {
            productSequenceNumber = this.badCodeModel.vehicleSn;
          }
          let params = {
            productSequenceNumber: productSequenceNumber,
            objectType: this.badCodeModel.objectType == 'CARRIER' ? 'CARRIER' : 'PRODUCT'
          };
          getList(params).then((res) => {
            this.badCodeEntry(productSequenceNumber, 'input');
            if (this.badCodeModel.objectType == 'PRODUCT') {
              this.badCodeModel.productSequenceNumber = '';
            } else if (this.badCodeModel.objectType == 'PACKING') {
              this.badCodeModel.packingSn = '';
            } else if (this.badCodeModel.objectType == 'CARRIER') {
              this.badCodeModel.vehicleSn = '';
            }
            // this.$refs.badConfirmProperties.resetForm();
            // this.badCodeModel.objectType = 'PRODUCT';
            // this.badCodeModel.productSequenceNumber = '';
          });
          // this.focusSequenceNumber();
          done();
        }
      });
    },

    tableRowClassName({ row, rowIndex }) {
      let className = row.isCheck ? 'scan-entry-row' : '';
      return className;
    },

    /**
     * 不良code录入操作
     *
     */
    badCodeEntry(productSequenceNumber, type) {
      let data = this._cloneDeep(this.data);
      let items = this._remove(data, (item) => {
        return item.productSequenceNumber === productSequenceNumber && item.objectType == this.badCodeModel.objectType;
      }).map((item) => {
        item.isCheck = type === 'input' ? true : false;
        // item.failureName = type === 'input' ? badCodeItem.name : '';
        return item;
      });
      this.data = type === 'input' ? items.concat(data) : data.concat(items);
      this.filtersFailureSequenceNumber();
    },

    focusSequenceNumber() {
      this.$nextTick(() => {
        this.$refs.sequenceNumberProperties.focus();
      });
    },

    filtersFailureSequenceNumber() {
      this.selectionList = this._filter(this.data, (item) => {
        return item.isCheck === true;
      });
    },
    //录入序列号双击取消选中
    rowDblclick(row) {
      if (row.isCheck) {
        this.badCodeEntry(row.productSequenceNumber, 'cancel');
      }
    },
    viewDetail(idx, row) {
      this.isAuto = row.registrySource == '自动';
      this.rowData = structuredClone(row);
      this.activeName = 'first';
      this.viewDialog = true;
    },
    repairrecordOpen() {
      getCenterList({
        principal: this.user_id
      })
        .then((res) => {
          let data = res.data.data;
          if (data && data.length > 0) {
            this.properties.workshopId = data[0].workshopId;
            this.properties.repairStationId = data[0].id;
          } else {
            this.properties.workshopId = '';
            this.properties.repairStationId = '';
          }
        })
        .catch((err) => {});
    }
  }
};
</script>

<style scoped>
::v-deep .el-table .header-color {
  color: rgba(0, 0, 0, 0.85) !important;
}

::v-deep .el-table {
  height: 70vh;
}

::v-deep .el-table .scan-entry-row {
  background: #caf982;
}

.tdStyle {
  background: #fafafa;
  font-weight: 700;
  color: #909399;
  text-align: right;
  width: auto;
  padding-right: 20px;
  white-space: nowrap;
}

td {
  padding: 5px;
  border: 1px solid #ebeef5;
}

.footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
::v-deep .el-card__body {
  padding: 0;
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
